from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver.firefox.options import Options as FirefoxOptions
import time
import os
import platform
import random
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import ElementNotInteractableException, TimeoutException, NoSuchElementException
import argparse
import subprocess

# ===== 用户配置区域 - 开始 =====
#默认的cookie，如果未提供配置文件，则使用此cookie
DEFAULT_COOKIE_STRING = """替换为你自己的cookie"""

# 设置最大视频播放数量
MAX_VIDEOS = 70

# 是否使用无头模式（True为浏览器后台运行，False为浏览器前台显示）
HEADLESS_MODE = False

# 视频播放间隔时间（单位：秒）
VIDEO_INTERVAL = 5

# ===== 用户配置区域 - 结束 =====

# 目标页面URL
target_url = 'https://marketing.csdn.net/p/757413354b0d5a0bdf984c4aa7fc708e?pId=2973'
# 用于验证Cookie有效性的URL
COOKIE_VERIFY_URL = 'https://i.csdn.net/#/user-center/profile'
# 登录页面URL，用于检测是否被重定向到登录页
LOGIN_PAGE_URL = 'passport.csdn.net'

# 添加全局计数器变量
successful_video_count = 0
# 添加全局用户ID变量
current_user_id = ""

def detect_browser():
    """
    自动检测系统中可用的浏览器，优先Chrome，其次Firefox
    
    返回:
    tuple: (browser_type, browser_path, driver_path)
    """
    system = platform.system()
    print(f"检测到操作系统: {system}")
    
    # 根据不同操作系统设置可能的浏览器路径
    if system == "Linux":
        chrome_paths = [
            '/usr/bin/google-chrome',
            '/usr/bin/chromium-browser',
            '/usr/bin/chromium'
        ]
        chrome_driver_paths = [
            '/usr/bin/chromedriver',
            '/usr/local/bin/chromedriver'
        ]
        firefox_paths = [
            '/usr/bin/firefox'
        ]
        firefox_driver_paths = [
            '/usr/bin/geckodriver',
            '/usr/local/bin/geckodriver'
        ]
    elif system == "Windows":
        chrome_paths = [
            'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
            'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'
        ]
        chrome_driver_paths = [
            'C:\\Program Files\\chromedriver\\chromedriver.exe',
            'C:\\Windows\\chromedriver.exe'
        ]
        firefox_paths = [
            'C:\\Program Files\\Mozilla Firefox\\firefox.exe',
            'C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe'
        ]
        firefox_driver_paths = [
            'C:\\Program Files\\geckodriver\\geckodriver.exe',
            'C:\\Windows\\geckodriver.exe'
        ]
    elif system == "Darwin":  # macOS
        chrome_paths = [
            '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
            '/Applications/Chromium.app/Contents/MacOS/Chromium'
        ]
        chrome_driver_paths = [
            '/usr/local/bin/chromedriver',
            '/usr/bin/chromedriver'
        ]
        firefox_paths = [
            '/Applications/Firefox.app/Contents/MacOS/firefox'
        ]
        firefox_driver_paths = [
            '/usr/local/bin/geckodriver',
            '/usr/bin/geckodriver'
        ]
    else:
        print(f"不支持的操作系统: {system}")
        return None, None, None
    
    # 优先检测Chrome
    for chrome_path in chrome_paths:
        if os.path.exists(chrome_path):
            print(f"找到Chrome浏览器: {chrome_path}")
            # 检测ChromeDriver
            for driver_path in chrome_driver_paths:
                if os.path.exists(driver_path):
                    print(f"找到ChromeDriver: {driver_path}")
                    return 'chrome', chrome_path, driver_path
            
            print("找到Chrome浏览器，但未找到ChromeDriver")
    
    # 如果没有找到Chrome，检测Firefox
    for firefox_path in firefox_paths:
        if os.path.exists(firefox_path):
            print(f"找到Firefox浏览器: {firefox_path}")
            # 检测GeckoDriver
            for driver_path in firefox_driver_paths:
                if os.path.exists(driver_path):
                    print(f"找到GeckoDriver: {driver_path}")
                    return 'firefox', firefox_path, driver_path
            
            print("找到Firefox浏览器，但未找到GeckoDriver")
    
    # 如果没有找到浏览器路径，但可能使用系统默认路径
    try:
        # 尝试检测是否可以使用默认Chrome
        from shutil import which
        chrome_cmd = which('chrome') or which('google-chrome') or which('chromium')
        if chrome_cmd:
            print(f"找到Chrome命令: {chrome_cmd}")
            chrome_driver = which('chromedriver')
            if chrome_driver:
                print(f"找到ChromeDriver命令: {chrome_driver}")
                return 'chrome', None, chrome_driver
        
        # 尝试检测是否可以使用默认Firefox
        firefox_cmd = which('firefox')
        if firefox_cmd:
            print(f"找到Firefox命令: {firefox_cmd}")
            gecko_driver = which('geckodriver')
            if gecko_driver:
                print(f"找到GeckoDriver命令: {gecko_driver}")
                return 'firefox', None, gecko_driver
    except:
        pass
    
    print("未找到任何支持的浏览器或驱动程序")
    return None, None, None

def visit_csdn_edu_page(cookie, browser_type=None):
    """
    访问CSDN教育页面并自动播放视频
    
    参数:
    browser_type (str): 浏览器类型，可选值为 'chrome' 或 'firefox'，如果为None则自动检测
    """
    # 如果未指定浏览器类型，自动检测
    if browser_type is None:
        browser_info = detect_browser()
        if browser_info[0]:
            browser_type, browser_path, driver_path = browser_info
            print(f"自动选择浏览器: {browser_type}")
        else:
            print("未能自动检测到支持的浏览器，请手动指定浏览器类型")
            print("支持的浏览器类型: chrome, firefox")
            return
    else:
        # 手动指定浏览器类型，但仍然自动检测路径
        browser_info = detect_browser()
        if browser_info[0] == browser_type:
            _, browser_path, driver_path = browser_info
        else:
            # 如果指定的浏览器类型与检测到的不一致，尝试查找指定类型
            if browser_type.lower() == 'chrome':
                browser_info = detect_browser()
                if browser_info[0] == 'chrome':
                    _, browser_path, driver_path = browser_info
                else:
                    print("未找到Chrome浏览器，请确保已安装")
                    return
            elif browser_type.lower() == 'firefox':
                browser_info = detect_browser()
                if browser_info[0] == 'firefox':
                    _, browser_path, driver_path = browser_info
                else:
                    print("未找到Firefox浏览器，请确保已安装")
                    return
            else:
                print(f"不支持的浏览器类型: {browser_type}")
                print("支持的浏览器类型: chrome, firefox")
                return
    
    try:
        if browser_type.lower() == 'chrome':
            # 设置Chrome选项
            browser_options = ChromeOptions()
            browser_options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36')
            
            # 根据配置决定是否使用无头模式
            if HEADLESS_MODE:
                browser_options.add_argument('--headless')
                print("Chrome浏览器使用无头模式（后台运行）")
            else:
                print("Chrome浏览器使用有界面模式（前台显示）")
            
            # 如果找到了浏览器路径，设置二进制文件路径
            if browser_path:
                browser_options.binary_location = browser_path
            
            # 初始化WebDriver
            service = ChromeService(driver_path)
            driver = webdriver.Chrome(service=service, options=browser_options)
            
        else:  # firefox
            # 设置Firefox选项
            browser_options = FirefoxOptions()
            browser_options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/119.0')
            
            # 根据配置决定是否使用无头模式
            if HEADLESS_MODE:
                browser_options.add_argument('--headless')
                print("Firefox浏览器使用无头模式（后台运行）")
            else:
                print("Firefox浏览器使用有界面模式（前台显示）")
            
            # 如果找到了浏览器路径，设置二进制文件路径
            if browser_path:
                browser_options.binary_location = browser_path
                
            # 初始化WebDriver
            service = FirefoxService(driver_path)
            driver = webdriver.Firefox(service=service, options=browser_options)
        
        # 访问CSDN并设置cookies
        process_page(cookie, driver)
        
    except Exception as e:
        print(f"{browser_type} WebDriver失败: {e}")
        print(f"请确保已安装{browser_type}浏览器和对应的WebDriver")

def process_page(cookie, driver):
    """处理CSDN页面的通用函数"""
    global successful_video_count
    
    # 先访问一个普通页面（不会立即跳转到登录页的页面）
    #print("正在访问CSDN个人信息页...")
    driver.get(COOKIE_VERIFY_URL)
    # 让网页加载一下，要不然cookie可能添加失败
    time.sleep(1)

    # 解析cookie字符串并添加到浏览器
    parse_and_add_cookies(driver, cookie)
    
    # 访问验证URL来验证Cookie
    #print(f"正在访问验证URL: {COOKIE_VERIFY_URL}")
    driver.get(COOKIE_VERIFY_URL)
    
    # 不再使用固定等待时间，而是立即验证Cookie
    # 验证Cookie是否有效
    if not verify_cookie_valid(driver):
        print("Cookie无效，程序退出！")
        driver.quit()
        return
    
    # 读取Cookie中的UserName，来获取当前用户ID
    global current_user_id
    current_user_id = ""
    for cookie in driver.get_cookies():
        if cookie['name'] == 'UserName':
            current_user_id = cookie['value']
            break
    #print(f"当前用户ID: {current_user_id}")

    # Cookie有效，访问目标页面
    print("Cookie验证有效，开始刷视频...\n")
    driver.get(target_url)
    
    # 8组课程对应的容器选择器列表
    container_selectors = [
        "#course-link-type3-kebgdaxfnj",
        "#course-link-type3-m0xgjhvy2p",
        "#course-link-type3-2mkekse06l0",
        "#course-link-type3-44icgnbq428",
        "#course-link-type3-9cmux4cwfh",
        "#course-link-type3-tttzhiwhws",
        "#course-link-type3-k18ynepewh",
        "#course-link-type3-buh5lva40k"
    ]
    
    print("\n正在等待课程页面完全加载...")
    # 检查最后一个容器是否存在，以确保页面完全加载
    try:
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, container_selectors[-1]))
        )
        print(f"课程页面完全加载成功，共找到 {len(container_selectors)} 组课程！\n")
    except TimeoutException:
        print("警告：最后一组课程未找到，页面可能未完全加载，但会尝试继续执行")
    
    # 强制启用随机访问，打乱容器顺序
    #print("\n打乱8组课程顺序，启动随机访问")
    random.shuffle(container_selectors)
    
    # 遍历所有容器
    for container_index, container_selector in enumerate(container_selectors):
        # 检查是否已达到目标视频数
        if successful_video_count >= MAX_VIDEOS:
            #print(f"\n已成功播放 {successful_video_count} 个视频，达到目标数量，程序退出！")
            break

        #print(f"\n当前尝试打开第 {container_index+1} 组: {container_selector}")
        
        try:
            # 等待容器加载
            container = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, container_selector))
            )
            
            # 查找容器内的所有视频链接
            video_links_selector = f"{container_selector} > div > div > ul > li"
            video_elements = driver.find_elements(By.CSS_SELECTOR, video_links_selector)
            
            #print(f"在第 {container_index+1} 组课程中共找到 {len(video_elements)} 个视频")
            
            # 遍历容器内的所有视频
            for video_index, video_element in enumerate(video_elements):
                # 检查是否已达到目标视频数
                if successful_video_count >= MAX_VIDEOS:
                    #print(f"\n已成功播放 {successful_video_count} 个视频，达到目标数量，程序退出！")
                    break
                    
                try:
                    #print(f"接下来，尝试处理 {len(video_elements)} 个视频中的第 {video_index+1}个")
                    
                    # 获取视频链接
                    link_element = video_element.find_element(By.TAG_NAME, "a")
                    video_url = link_element.get_attribute("href")
                    video_title = link_element.text.strip()
                    
                    if not video_url:
                        print(f"视频 {video_index+1} 没有有效链接，跳过")
                        continue
                    
                    #print(f"本组课程标题: {video_title}")
                    #print(f"当前课程链接: {video_url}")
                    #print("开始访问视频链接...")
                    # 在新窗口中打开视频链接
                    driver.execute_script("window.open(arguments[0]);", video_url)
                    
                    # 切换到新窗口
                    driver.switch_to.window(driver.window_handles[-1])
                    
                    # 检查页面结构
                    process_video_page(driver)
                    
                    # 关闭当前视频窗口
                    driver.close()
                    
                    # 切回主窗口
                    driver.switch_to.window(driver.window_handles[0])
                    
                except Exception as e:
                    print(f"处理视频 {video_index+1} 时出错: {e}")
                    
                    # 确保回到主窗口
                    if len(driver.window_handles) > 1:
                        driver.close()
                        driver.switch_to.window(driver.window_handles[0])
            
        except TimeoutException:
            print(f"容器 {container_selector} 加载超时")
        except NoSuchElementException:
            print(f"找不到容器 {container_selector}")
        except Exception as e:
            print(f"处理容器 {container_index+1} 时出错: {e}")
    
    # 关闭浏览器
    driver.quit()

def verify_cookie_valid(driver):
    """验证Cookie是否有效"""
    print("\n正在验证Cookie有效性...")
    
    try:
        # 检查是否有余额信息，这是登录状态的明确标志
        try:
            # 使用更短的超时时间，加快验证速度
            WebDriverWait(driver, 2).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "#user-center-container > div.container-right > div > div.profile-header > div.general-info > div.general-info-b > div.c-coin > span.c-coin-num"))
            )
            #print("Cookie有效！查到余额了，确认已登录")
            return True
        except:
            # 如果找不到余额信息，再次检查是否被重定向到登录页
            current_url = driver.current_url
            if LOGIN_PAGE_URL in current_url:
                print(f"Cookie无效！当前URL: {current_url}")
                print("被重定向到登录页面，请更新Cookie")
                return False
            
            # 如果找不到余额信息，尝试其他登录状态指标
            try:
                # 尝试查找其他登录后才会显示的元素
                WebDriverWait(driver, 2).until(
                    EC.presence_of_element_located((By.CSS_SELECTOR, ".user-info, .user-profile, .user-name"))
                )
                print("Cookie有效！成功验证登录状态")
                return True
            except:
                # 再次检查是否被重定向到登录页
                current_url = driver.current_url
                if LOGIN_PAGE_URL in current_url:
                    print(f"Cookie无效！当前URL: {current_url}")
                    print("被重定向到登录页面，请更新Cookie")
                    return False
                
                # 如果找不到登录元素，但也没有重定向到登录页，进一步检查
                if "登录" in driver.title or "注册" in driver.title:
                    print("Cookie无效！页面标题包含'登录'或'注册'")
                    return False
                
                # 尝试查找登录按钮
                try:
                    login_buttons = driver.find_elements(By.XPATH, "//a[contains(text(), '登录')] | //button[contains(text(), '登录')]")
                    if login_buttons:
                        print("Cookie无效！页面包含登录按钮")
                        return False
                except:
                    pass
                
                # 如果没有明确的登录指示，但也没有找到用户信息，给出警告但继续执行
                print("警告：无法确定Cookie是否有效，但未被重定向到登录页，将继续执行")
                return True
            
    except Exception as e:
        print(f"验证Cookie时出错: {e}")
        print("无法验证Cookie有效性，将尝试继续执行")
        return True

def parse_and_add_cookies(driver, cookie_string):
    """解析完整的cookie字符串并添加到浏览器"""
    #print("正在解析并添加cookies...")
    
    # 分割cookie字符串为单个cookie项
    cookie_items = cookie_string.split(';')
    
    # 关键cookie列表，这些是必须的
    essential_cookies = ['UN', 'UserName', 'UserToken', 'UserInfo', 'UserNick', 'uuid_tt_dd']
    essential_values = {}
    
    # 遍历所有cookie项
    for item in cookie_items:
        item = item.strip()
        if not item:
            continue
            
        # 分割名称和值
        try:
            name, value = item.split('=', 1)
            name = name.strip()
            value = value.strip()
            
            # 检查是否为关键cookie
            if name in essential_cookies:
                essential_values[name] = value
                
            # 添加cookie到浏览器
            try:
                cookie = {'name': name, 'value': value, 'domain': '.csdn.net'}
                driver.add_cookie(cookie)
            except Exception as e:
                # 某些cookie可能无法添加，这是正常的
                pass
                
        except ValueError:
            # 某些cookie可能格式不正确，跳过
            continue
    
    # 检查是否所有关键cookie都已添加
    missing_cookies = [name for name in essential_cookies if name not in essential_values]
    if missing_cookies:
        print(f"警告：缺少以下关键cookie: {', '.join(missing_cookies)}")
        print("登录可能会失败，请确保提供完整的cookie")
    else:
        pass
        #print("所有关键cookie已成功添加")

def video_ready(driver):
	return driver.execute_script("""
	var video = document.querySelector('video');
	return video && video.readyState >= 3;
	""")

def video_playing(driver):
    return driver.execute_script("""
    const video = document.querySelector('video');
    if (!video) return false;
    return !video.paused && !video.ended && video.readyState >= 3;
    """)

def process_video_page(driver):
    """处理视频页面，检查视频是否存在并播放"""
    global successful_video_count
    
    # 等待视频播放器加载完成（使用动态等待替代固定等待）
    #print("等待视频加载...")
    try:
        # 最多等待10秒直到播放器加载完成
        WebDriverWait(driver, 10).until(video_ready)
        #print("视频加载完成")
    except Exception as e:
        print(f"处理视频页面时出错: {e}")
        return

    # 开始播放视频
    #print("开始播放视频...")
    #play_video(driver)

    """处理视频切换逻辑，支持多章节多视频结构"""    
    try:
        # 首先检查是否有章节列表
        chapter_selector = "#playBox > div.catalogue-container > div > div > div > div > div > div.ivu-tabs-content > div:nth-child(1) > div > ul > li"
        chapters = driver.find_elements(By.CSS_SELECTOR, chapter_selector)
        
        # 检查是否有子视频列表（判断是否为章节）
        has_chapters = False
        for chapter in chapters:
            # 尝试查找章节下的视频列表
            try:
                sub_videos = chapter.find_elements(By.CSS_SELECTOR, "ul > li")
                if len(sub_videos) > 0:
                    has_chapters = True
                    break
            except:
                continue
        
        if has_chapters:
            # 多章节结构
            #print(f"发现多章节结构，共 {len(chapters)} 个章节")
            
            # 遍历所有章节
            for chapter_index, chapter in enumerate(chapters):
                # 检查是否已达到目标视频数
                if successful_video_count >= MAX_VIDEOS:
                    #print(f"\n已成功播放 {successful_video_count} 个视频，达到目标数量，程序退出！")
                    return
                    
                try:
                    # 尝试多种可能的章节标题选择器
                    chapter_title = "未知章节"
                    for title_selector in ["div.chapter-title", "div.title", ".title", "span.title", "span"]:
                        try:
                            title_element = chapter.find_element(By.CSS_SELECTOR, title_selector)
                            if title_element and title_element.text.strip():
                                chapter_title = title_element.text.strip()
                                break
                        except:
                            continue
                    
                    # 如果所有选择器都失败，尝试使用章节的文本内容
                    if chapter_title == "未知章节":
                        try:
                            chapter_title = chapter.text.strip().split('\n')[0]
                        except:
                            pass
                    
                    #print(f"处理章节 {chapter_index+1}/{len(chapters)}: {chapter_title}")
                    
                    # 如果不是第一个章节，需要先点击展开章节
                    if chapter_index > 0:
                        try:
                            #print(f"点击展开章节 {chapter_index+1}")
                            chapter.click()
                        except Exception as e:
                            print(f"点击章节失败: {e}")
                            continue
                    
                    # 查找章节下的所有视频
                    try:
                        sub_videos = chapter.find_elements(By.CSS_SELECTOR, "ul > li")
                        #print(f"在章节 {chapter_index+1} 中找到 {len(sub_videos)} 个视频")
                        
                        # 遍历章节下的所有视频
                        for sub_video_index, sub_video in enumerate(sub_videos):
                            # 检查是否已达到目标视频数
                            if successful_video_count >= MAX_VIDEOS:
                                #print(f"\n已成功播放 {successful_video_count} 个视频，达到目标数量，程序退出！")
                                return
                                
                            try:
                                sub_video_title = sub_video.text.strip()
                                #print(f"处理子视频 {sub_video_index+1}/{len(sub_videos)}: {sub_video_title}")
                                
                                # 点击选择视频
                                try:
                                    #print(f"点击选择子视频 {sub_video_index+1}")
                                    sub_video.click()
                                    time.sleep(1)  # 等待视频切换
                                    
                                    # 播放当前视频
                                    play_video(driver)
                                    
                                except Exception as e:
                                    print(f"点击子视频失败: {e}")
                                    continue
                                
                            except Exception as e:
                                print(f"处理子视频 {sub_video_index+1} 时出错: {e}")
                        
                    except Exception as e:
                        print(f"获取章节下视频列表失败: {e}")
                
                except Exception as e:
                    print(f"处理章节 {chapter_index+1} 时出错: {e}")
            
        else:
            # 单章节多视频结构或单视频结构
            if len(chapters) > 1:
                #print(f"发现单章节多视频结构，共 {len(chapters)} 个视频")
                
                # 遍历所有视频
                for video_index, video in enumerate(chapters):
                    # 检查是否已达到目标视频数
                    if successful_video_count >= MAX_VIDEOS:
                        #print(f"\n已成功播放 {successful_video_count} 个视频，达到目标数量，程序退出！")
                        return
                        
                    try:
                        #print(f"处理视频 {video_index+1}/{len(chapters)}")
                        
                        # 如果不是第一个视频，需要先点击切换
                        if video_index > 0:
                            try:
                                #print(f"点击切换到视频 {video_index+1}")
                                video.click()
                                time.sleep(1)  # 等待视频切换
                            except Exception as e:
                                print(f"点击视频失败: {e}")
                                continue
                        
                        # 播放当前视频
                        play_video(driver)
                        
                    except Exception as e:
                        print(f"处理视频 {video_index+1} 时出错: {e}")
            else:
                print("只有一个视频，直接播放")
                play_video(driver)
    
    except NoSuchElementException:
        print("未找到视频列表，按单个视频处理")
        play_video(driver)
    except Exception as e:
        print(f"检查视频页面结构时出错: {e}")
        # 尝试直接播放视频
        play_video(driver)

def play_video(driver):
    """播放视频的通用函数"""
    global successful_video_count

    if video_playing(driver):
        #print("视频已经在播放中，跳过播放")
        # 增加成功播放计数
        successful_video_count += 1
        print(f"当前已成功播放 {successful_video_count}/{MAX_VIDEOS} 个视频，等待{VIDEO_INTERVAL}秒后切换下一个")
        time.sleep(VIDEO_INTERVAL)
        return
    else:
        #print("视频未在播放中，尝试播放")
        play_buttons = driver.find_elements(By.CSS_SELECTOR, "#csdnPlayer > xg-start > div.xgplayer-icon-play")
        if play_buttons:
            play_button = play_buttons[0]
            #print("找到播放按钮，点击开始播放...")
            try:
                if play_button.is_displayed() and play_button.is_enabled():
                    play_button.click()
                    #print("成功点击播放按钮")
                else:
                    pass
                    #print("播放按钮不可用或不可见，可能已经自动播放了")
            except Exception as e:
                print(f"点击播放按钮时出错: {e}")
                return
        else:
            pass
            #print("未找到播放按钮，可能已经自动播放了")

        try:
            # 最多等待10秒直到播放器加载完成
            WebDriverWait(driver, 10).until(video_playing)
            #print("视频开始播放")
            # 增加成功播放计数
            successful_video_count += 1
            print(f"当前已成功播放 {successful_video_count}/{MAX_VIDEOS} 个视频，等待{VIDEO_INTERVAL}秒后切换下一个")
            time.sleep(VIDEO_INTERVAL)
        except Exception as e:
            print(f"等待视频起播时出错: {e}")
            return
        except TimeoutException:
            print("等待视频起播，视频可能未正常加载")
            return

if __name__ == "__main__":
    # 记录开始时间
    start_time = time.time()

    public_ip = subprocess.check_output(['curl', '-s', 'ifconfig.me']).decode('utf-8').strip()
    print(f"当前公网IP: {public_ip}")

    parser = argparse.ArgumentParser(description="CSDN Auto Play Video Script.")
    parser.add_argument(
        "-c", "--config",
        type=str,
        help="Path to a JSON configuration file containing the 'cookie_string'."
    )
    args = parser.parse_args()

    cookie_string = DEFAULT_COOKIE_STRING
    if args.config:
        try:
            with open(args.config, 'r', encoding='utf-8') as f:
                loaded_cookie_string = f.read().strip() # 直接读取文件内容
                if loaded_cookie_string:
                    cookie_string = loaded_cookie_string # 更新全局 cookie_string
                    print(f"已从配置文件 '{args.config}' 加载Cookie。")
                else:
                    print(f"警告：配置文件 '{args.config}' 为空。将使用代码中定义的默认Cookie。")
        except FileNotFoundError:
            print(f"错误：配置文件 '{args.config}' 未找到。将使用代码中定义的默认Cookie。")
        except Exception as e:
            print(f"错误：加载配置文件 '{args.config}' 时发生未知错误: {e}。将使用代码中定义的默认Cookie。")
    else:
        print("未指定配置文件。将使用代码中定义的默认Cookie。")

    # 启动刷视频任务
    visit_csdn_edu_page(cookie_string)

    # 计算并显示总耗时
    end_time = time.time()
    total_time = end_time - start_time
    hours, remainder = divmod(total_time, 3600)
    minutes, seconds = divmod(remainder, 60)

    print(f"成功为用户 {current_user_id} 在公网ip：{public_ip} 环境下播放 {successful_video_count} 个视频, 用时：{int(hours)}小时{int(minutes)}分钟{int(seconds)}秒")
